package org.raymond.iworks.study.netty.atguigu.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
// TextWebSocketFrame,文本帧
@Slf4j
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("{} channelRead0", ctx.name());
        log.info("收到数据: {}", msg.text());

        Channel channel = ctx.channel();
        channel.writeAndFlush(new TextWebSocketFrame("服务端收到消息了"));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("{} handlerAdded", ctx.name());
        log.info("连接建立 channel id: {} {}", ctx.channel().id().asLongText(), ctx.channel().id().asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("{} handlerRemoved", ctx.name());
        log.info("连接断开 channel id: {} {}", ctx.channel().id().asLongText(), ctx.channel().id().asShortText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("{} exceptionCaught", ctx.name());
        log.error("{}", cause.getMessage());
        ctx.close();
    }
}
